<template>
    <!-- 搜索方法 -->
    <el-form :inline="true" :model="StudentData.query" class="demo-form-inline">
        <el-form-item label="name">
            <el-input v-model="StudentData.query.name" placeholder="name" clearable />
        </el-form-item>
        <el-form-item label="session">
            <el-input v-model="StudentData.query.session" placeholder="session" clearable />
        </el-form-item>
        <el-form-item label="status">
            <el-input v-model="StudentData.query.status" placeholder="status" clearable />
        </el-form-item>
        <el-form-item label="age">
            <el-input v-model="StudentData.query.age" placeholder="age" clearable />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="Query">查询</el-button>
            <el-button type="primary" @click="QueryReset">重置表单</el-button>
        </el-form-item>
    </el-form>

    <!-- 按钮组 -->
    <el-button type="primary" @click="handleAdd">新增</el-button>
    <el-button type="primary" @click="handleDeleteList(PageData.multipleSelection)">批量删除</el-button>

    <!-- 列表 -->
    <el-table :data="StudentData.studentList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" />
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="年龄" align="center" prop="age" />
        <el-table-column label="年级" align="center" prop="grade" />
        <el-table-column label="导师名字" align="center" prop="teacherName" />
        <el-table-column label="学生状态" align="center" prop="status" />
        <el-table-column label="哪一届？" align="center" prop="session" />
        <el-table-column label="学生类型" align="center" prop="type" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
                <el-button type="text" icon="Edit" @click="handleUpdate(scope.row.id)">修改
                </el-button>
                <el-button type="text" icon="Delete" @click="handleDelete(scope.row.id)">删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination layout="prev, pager, next" v-model:page-size="PageData.limit" v-model:total="PageData.total"
        v-show="PageData.total > 0" v-model:current-page="PageData.page" @current-change="studentList" />

    <!-- 弹框 修改  -->
    <el-dialog v-model="PageData.upDateDialog" title="Tips" width="30%">
        <el-form ref="studentRefUpdate" :model="StudentData.form" :rules="rules" label-width="80px">
            <el-form-item label="姓名 " prop="name">
                <el-input v-model="StudentData.form.name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="年龄" prop="age">
                <el-input v-model="StudentData.form.age" placeholder="请输入年龄" />
            </el-form-item>
            <el-form-item label="年级" prop="grade">
                <el-input v-model="StudentData.form.grade" placeholder="请输入年级" />
            </el-form-item>
            <el-form-item label="导师名字" prop="teacherName">
                <el-input v-model="StudentData.form.teacherName" placeholder="请输入导师名字" />
            </el-form-item>
            <el-form-item label="哪一届？" prop="session">
                <el-input v-model="StudentData.form.session" placeholder="请输入哪一届？" />
            </el-form-item>
            <el-form-item label="学生类型" prop="type">
                <el-input v-model="StudentData.form.type" placeholder="请输入您的学位" />
            </el-form-item>
            <span class="dialog-footer">
                <el-button @click="PageData.upDateDialog = false">Cancel</el-button>
                <el-button type="primary" @click="commitUpdate('update', studentRefUpdate)">
                    确定提交
                </el-button>
            </span>
        </el-form>
    </el-dialog>

    <!-- 弹框 新增  -->
    <el-dialog v-model="PageData.addDialog" title="Tips" width="30%">
        <el-form ref="studentRefAdd" :model="StudentData.form" :rules="rules" label-width="80px">
            <el-form-item label="姓名" prop="name">
                <el-input v-model="StudentData.form.name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="年龄" prop="age">
                <el-input v-model="StudentData.form.age" placeholder="请输入年龄" />
            </el-form-item>
            <el-form-item label="年级" prop="grade">
                <el-input v-model="StudentData.form.grade" placeholder="请输入年级" />
            </el-form-item>
            <el-form-item label="导师名字" prop="teacherName">
                <el-input v-model="StudentData.form.teacherName" placeholder="请输入导师名字" />
            </el-form-item>
            <el-form-item label="哪一届？" prop="session">
                <el-input v-model="StudentData.form.session" placeholder="请输入哪一届？" />
            </el-form-item>
            <el-form-item label="学生类型" prop="type">
                <el-input v-model="StudentData.form.type" placeholder="请输入您的学位" />
            </el-form-item>
            <span class="dialog-footer">
                <el-button @click="PageData.addDialog = false">返回</el-button>
                <el-button type="primary" @click="commitUpdate('add', studentRefAdd)">
                    确定提交
                </el-button>
            </span>
        </el-form>

    </el-dialog>

</template>
<script lang='ts' setup>
// 导包
import { QueryStudent, listStudent, getStudent, delStudent, addStudent, updateStudent, delListStudent } from "../request/api/studentApi/student";
import { Student } from '../interface/Student'
import { reactive, ref, toRefs } from 'vue'
import { ElMessageBox, ElMessage, FormRules, FormInstance } from 'element-plus'
import { de } from "element-plus/es/locale";

// ============================= 定义数据 ====================================== //

// 表单校验数据
const studentRefAdd = ref<FormInstance>()
const studentRefUpdate = ref<FormInstance>()

// 定义 页面必要的数据
let PageData = reactive({
    // 弹窗 修改
    upDateDialog: false,
    addDialog: false,
    // 复选框数据，表格选择
    multipleSelection: [],
    // 分页器 数据
    page: 1,
    limit: 10,
    total: 0,
})


// 定义后端实体数据 
let StudentData = reactive({
    studentList: [],
    form: {
        id: "",
        name: "",
        age: 0,
        grade: "",
        teacherName: "",
        status: "",
        session: "",
        type: ""
    },
    query: {
        id: null,
        name: null,
        age: null,
        grade: null,
        teacherName: null,
        status: null,
        session: null,
        type: null
    }
})

// ============================= 定义页面使用的函数 ====================================== //

// 表单规则校验
const rules = reactive<FormRules>({
    name: [
        { required: true, message: '请输入姓名！', trigger: 'blur' },
        { min: 3, max: 5, message: '姓名长度不符合！', trigger: 'blur' },
    ],
    age: [
        {
            required: true,
            message: '请输入年龄！',
            trigger: 'blur',
        },
    ],
    grade: [
        {
            required: true,
            message: '请输入年级！',
            trigger: 'blur',
        },
    ],
    teacherName: [
        {
            required: true,
            message: '请输入导师姓名！',
            trigger: 'blur',
        },
    ],
    session: [
        {
            required: true,
            message: '请填入您是哪一届的学生！',
            trigger: 'blur',
        },
    ],
    type: [
        {
            required: true,
            message: '请输入您的学位',
            trigger: 'blur',
        },
    ]
})

// 多选框选中数据
const handleSelectionChange = (val: never[]) => {
    PageData.multipleSelection = val
}

// 搜索框重置表单
const QueryReset = () =>{
    StudentData.query = {
        id: null,
        name: null,
        age: null,
        grade: null,
        teacherName: null,
        status: null,
        session: null,
        type: null
    }
}

// ============================= 调用后端函数 ====================================== //

// 搜索方法
let Query = () => {
    QueryStudent(StudentData.query,PageData.page, PageData.limit).then(res => {
        console.log(res.data);
        StudentData.studentList = res.data.data.data
        PageData.total = res.data.data.total
        ElMessage({
            type: 'success',
            message: '查询成功',
        })
    })
}

// 列表数据获取
let studentList = () => {
    listStudent(PageData.page, PageData.limit).then(res => {
        console.log(res.data.data)
        // 渲染列表
        StudentData.studentList = res.data.data.data
        // 分页器数量
        PageData.total = res.data.data.total
    })

}
// 新增
let handleAdd = () => {
    // 开启的时候先把数据清理干净
    StudentData.form = {
        id: "",
        name: "",
        age: 0,
        grade: "",
        teacherName: "",
        status: "",
        session: "",
        type: ""
    }
    PageData.addDialog = true;
}
// 修改
let handleUpdate = (id: string) => {
    getStudent(id).then(res => {
        console.log(res.data.data)
        // 将数据渲染到对话框
        StudentData.form = res.data.data
    })
    PageData.upDateDialog = true;

}

// 删除 真删
let handleDelete = (id: string) => {
    ElMessageBox.confirm(
        '确认删除这些数据吗？注意：是真删！',
        'Warning', {
        confirmButtonText: '确认',
        cancelButtonText: '返回',
        type: 'warning',
    }
    ).then(() => {
        delStudent(id).then(res => {
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
            // 修改成功后需要进行刷新页面！
            studentList()
        }).catch(err => {
            ElMessage({
                type: 'error',
                message: '删除失败: ' + err,
            })
        })

    })
}

// 删除 批量删除 真删
let handleDeleteList = (Student: Student[]) => {
    let idList = Student.map(i => i.id).join(",")
    console.log("ids === > ", idList);
    delListStudent(idList).then(res => {
        ElMessage({
            type: 'success',
            message: '删除成功',
        })
        // 修改成功后需要进行刷新页面！
        studentList()
    }).catch(err => {
        ElMessage({
            type: 'error',
            message: '删除失败: ' + err,
        })
    })

}

// 弹窗提交事件 --- add or update 
const commitUpdate = (flag: string, studentRef: any) => {
    // 表单校验：
    if (!studentRef) return
    studentRef.validate((valid: boolean) => {
        if (valid) {
            // 调用 接口
            if (flag === "update") {
                ElMessageBox.confirm(
                    '确认修改此数据吗',
                    'Warning',
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '返回',
                        type: 'warning',
                    }
                )
                    .then(() => {
                        // 调用修改 接口 -- 开始 todo
                        updateStudent(StudentData.form).then(res => {
                            console.log("修改成功！")
                            PageData.upDateDialog = false // 关闭对话框 
                            ElMessage({
                                type: 'success',
                                message: '修改成功',
                            })
                            // 修改成功后需要进行刷新页面！
                            studentList()
                        }).catch(err => {
                            ElMessage({
                                type: 'warning',
                                message: '修改失败: ' + err,
                            })
                        })
                        // 调用修改 接口 -- 结束
                    })
            } else {
                // 调用新增接口
                addStudent(StudentData.form).then(res => {
                    ElMessage({
                        type: 'success',
                        message: '新增成功',
                    })
                    PageData.addDialog = false // 关闭对话框 
                }).catch(err => {
                    ElMessage({
                        type: 'warning',
                        message: '新增失败: ' + err,
                    })
                })

            }
        } else {
            ElMessage({
                type: 'error',
                message: '请检查表单！',
            })
            return false
        }
    })




}

// ============================= 页面初始化调用函数  ====================================== //  
studentList()
</script>
 
<style lang="less" scoped>

</style>



